﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FDSimpleModelGenerator.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace FDSimpleModelGenerator.Common.Mvc.Middlewares
{
    /// <summary>
    /// 全局异常
    /// </summary>
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception e)
            {
                var log = context.RequestServices.GetService<ILog<GlobalExceptionMiddleware>>();
                log.Error($"{e.Message}:{e.Source}");
                throw;
            }
        }
    }
}
